/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: OptionApi.java
 *   @Date: 1/15/19 5:35 PM
 *   @Author: chenjun
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.sdk.trade;

import android.text.TextUtils;

import java.util.List;

import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.constant.Fields;
import io.bhex.baselib.network.BParamsBuilder;
import io.bhex.baselib.network.HttpUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.params.GetParams;
import io.bhex.baselib.network.params.PostParams;
import io.bhex.baselib.network.response.ResultResponse;
import io.bhex.sdk.Urls;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.data_manager.TradeDataManager;
import io.bhex.sdk.quote.bean.OptionCoinPairBean;
import io.bhex.sdk.quote.bean.OptionSymbolStatusBean;
import io.bhex.sdk.socket.NetWorkObserver;
import io.bhex.sdk.trade.bean.AssetRecordResponse;
import io.bhex.sdk.trade.bean.CreateOrderRequest;
import io.bhex.sdk.trade.bean.OpenOrderResponse;
import io.bhex.sdk.trade.bean.OptionAssetListResponse;
import io.bhex.sdk.trade.bean.OptionAssetListSocketResponse;
import io.bhex.sdk.trade.bean.OptionDeliveryRecordResponse;
import io.bhex.sdk.trade.bean.OptionFeeResponse;
import io.bhex.sdk.trade.bean.OptionHistoryResponse;
import io.bhex.sdk.trade.bean.OptionHoldOrderResponse;
import io.bhex.sdk.trade.bean.OptionIndicesResponse;
import io.bhex.sdk.trade.bean.OrderBean;
import io.bhex.sdk.trade.bean.OrderDealDetailResponse;

public class OptionApi {
    public static void SubOptionBalanceData(final NetWorkObserver<List<OptionAssetListResponse.OptionAssetBean>> observer){
        if(UserInfo.isLogin() == false)
            return;

        TradeDataManager.GetInstance().RequestOptionBalance(new NetWorkObserver<OptionAssetListSocketResponse>(){

            @Override
            public void onShowUI(OptionAssetListSocketResponse response) {
                if(response != null && response.data != null){
                    if(observer != null)
                        observer.onShowUI(response.data);
                }
            }

            @Override
            public void onError(String response) {
                if(observer != null)
                    observer.onError(response);

            }
        }, new NetWorkObserver<OptionAssetListResponse>(){

            @Override
            public void onShowUI(OptionAssetListResponse response) {
                if(response != null && response.array != null){
                    if(observer != null)
                        observer.onShowUI(response.array);
                }
            }

            @Override
            public void onError(String response) {
                if(observer != null)
                    observer.onError(response);
            }
        });
    }

    /**
     * RequestBalanceData
     * @param observer
     */
    public static void RequestOptionBalanceData(SimpleResponseListener<OptionAssetListResponse> observer){
        if(UserInfo.isLogin() == false)
            return;

        TradeDataManager.GetInstance().getRequestOptionCurrentBalance( observer);

        PostParams params = BParamsBuilder.post()
                .url(Urls.API_ACCOUNT_GET_OPTION_LIST)
                .addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
//                .addParam(Fields.FIELD_SYMBOL, )

//                .addParam(Fields.FIELD_ORDER_ID_PAGE,)
//                .addParam(Fields.FIELD_START_TIME,)
//                .addParam(Fields.FIELD_END_TIME,)
                .build();
        HttpUtils.getInstance().request(params, OptionAssetListResponse.class, observer);
    }

    /**
     * RequestTokenBalance  should not Unsub
     * @param token
     * @param observer
     */
    public static void SubOptionTokenBalanceChange(String token, SimpleResponseListener<OptionAssetListResponse.OptionAssetBean> observer){
        if(UserInfo.isLogin() == false)
            return;

        TradeDataManager.GetInstance().RequestOptionTokenBalance(token, observer);
    }

    /**
     * SubSymbolOrder  should not Unsub
     * @param symbol
     * @param observer
     */
    public static void SubOptionSymbolOrderChange(String symbol, SimpleResponseListener<OpenOrderResponse> observer){

        TradeDataManager.GetInstance().RequestOptionSymbolOrder(symbol, observer);
    }

    /**
     * SubSymbolOrder  should not Unsub
     * @param symbol
     * @param observer
     */
    public static void SubOptionHoldOrderChange(String symbol, SimpleResponseListener<OptionHoldOrderResponse> observer){

        TradeDataManager.GetInstance().RequestOptionHoldOrder(symbol, observer);
    }

    /**
     * RequestOrder  should not Unsub
     * @param observer
     */
    public static void SubOptionOrderChange( SimpleResponseListener<OpenOrderResponse> observer){

        TradeDataManager.GetInstance().RequestOptionOrder(observer);
    }

    /**
     * RequestOrder  should not Unsub
     * @param observer
     */
    public static void SubOptionHoldOrderChange( SimpleResponseListener<OptionHoldOrderResponse> observer){

        TradeDataManager.GetInstance().RequestOptionHoldOrder(observer);
    }



    /**
     * 获取历史期权
     *
     */
    public static void RequestOptionHistoryDelivery(int page, SimpleResponseListener<OptionHistoryResponse> observer) {

        PostParams.Builder builder = new BParamsBuilder().post();
        builder.url(Urls.API_OPTION_HISTORY_DELIVERY)
                .addParam(Fields.FIELD_LIMIT,AppData.Config.PAGE_LIMIT);
        if(page <= 1)
            builder.addParam("page", 1);
        else
            builder.addParam("page", page);
        PostParams params = builder.build();
        HttpUtils.getInstance().request(params, OptionHistoryResponse.class, observer);

    }

    public static void RequestOptionOpenOrder(String symbols, String pageId, SimpleResponseListener<OpenOrderResponse> observer){

        PostParams.Builder builder = new BParamsBuilder().post();
        builder.url(Urls.API_OPTION_ORDER_OPEN_ORDERS)
                //.addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
                .addParam(Fields.FIELD_LIMIT, 50);
        if(!TextUtils.isEmpty(symbols))
            builder.addParam("symbol_id",symbols);
        if(!TextUtils.isEmpty(pageId))
            builder.addParam(Fields.FIELD_ORDER_ID_PAGE_FROM, pageId);
        PostParams params = builder.build();
        HttpUtils.getInstance().request(params, OpenOrderResponse.class, observer);
    }


    public static void RequestOptionCancelOrder(String orderId, SimpleResponseListener<OrderBean> listener){
        PostParams params = BParamsBuilder.post()
                .url(Urls.API_OPTION_ORDER_CANCEL)
                //.addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
                .addParam(Fields.FIELD_CLIENT_ORDER_ID, System.currentTimeMillis() + "")
                .addParam(Fields.FIELD_ORDER_ID, orderId)
                .build();
        HttpUtils.getInstance().request(params, OrderBean.class, listener);
    }

    /**
     * 获取历史委托
     *
     */
    public static void RequestOptionHistoryOrders(String symbols, String pageId,  SimpleResponseListener<OpenOrderResponse> observer) {

        PostParams.Builder builder = new BParamsBuilder().post();
        builder.url(Urls.API_OPTION_ORDER_TRADE_ORDERS)
                .addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
                .addParam(Fields.FIELD_LIMIT,AppData.Config.PAGE_LIMIT);
        if(!TextUtils.isEmpty(symbols))
            builder.addParam("symbol_id",symbols.toUpperCase());
        if(!TextUtils.isEmpty(pageId))
            builder.addParam(Fields.FIELD_ORDER_ID_PAGE_FROM, pageId);
        PostParams params = builder.build();
        HttpUtils.getInstance().request(params, OpenOrderResponse.class, observer);

    }

    /**
     * 获取持仓 期权id（支持多个，用逗号隔开） 例如: W_BTC_CALL_0118,W_BTC_CALL_0118
     *
     */
    public static void RequestOptionHoldOrder(String symbols, String pageId, SimpleResponseListener<OptionHoldOrderResponse> observer) {

        PostParams.Builder builder = new BParamsBuilder().post();
        builder.url(Urls.API_OPTION_HOLD_ORDERS)
                //.addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
                .addParam(Fields.FIELD_LIMIT,50);
        if(!TextUtils.isEmpty(symbols))
            builder.addParam("symbol_ids",symbols);
        if(!TextUtils.isEmpty(pageId))
            builder.addParam(Fields.FIELD_BALANCE_ID_PAGE_FROM, pageId);
        PostParams params = builder.build();
        HttpUtils.getInstance().request(params, OptionHoldOrderResponse.class, observer);

    }

    /**
     * 获取历史成交
     *
     */
    public static void RequestOptionDealRecord(String symbols, String pageId,SimpleResponseListener<OrderDealDetailResponse> observer) {

        PostParams.Builder builder = new BParamsBuilder().post();
        builder.url(Urls.API_OPTION_ORDER_DEAL_ORDERS)
                .addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
                .addParam(Fields.FIELD_LIMIT,AppData.Config.PAGE_LIMIT);
        if(!TextUtils.isEmpty(symbols))
            builder.addParam("symbol_id",symbols);
        if(!TextUtils.isEmpty(pageId))
            builder.addParam(Fields.FIELD_TRADE_ID_PAGE_FROM, pageId);
        PostParams params = builder.build();
        HttpUtils.getInstance().request(params, OrderDealDetailResponse.class, observer);

    }

    /**
     * 获取交割
     *
     */
    public static void RequestOptionHistoryDeliveryRecord(String symbols, String pageId, SimpleResponseListener<OptionDeliveryRecordResponse> observer) {

        PostParams.Builder builder = new BParamsBuilder().post();
        builder.url(Urls.API_OPTION_ORDER_DELIVERY_ORDERS)
                .addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
                .addParam(Fields.FIELD_LIMIT,AppData.Config.PAGE_LIMIT);
        if(!TextUtils.isEmpty(symbols))
            builder.addParam("symbol_id",symbols);
        if(!TextUtils.isEmpty(pageId))
            builder.addParam(Fields.FIELD_SETTLEMENT_ID_PAGE_FROM, pageId);
        PostParams params = builder.build();
        HttpUtils.getInstance().request(params, OptionDeliveryRecordResponse.class, observer);

    }

    /**
     * RequestOrderMatchInfo
     * @param orderId
     * @param orderPageId
     * @param observer
     */
    public static void RequestOptionOrderMatchInfo(String orderId, String orderPageId, SimpleResponseListener<OrderDealDetailResponse> observer){
        PostParams.Builder builder = new BParamsBuilder().post();
        builder.url(Urls.API_OPTION_ORDER_MATCH_INFO)
                .addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
                .addParam(Fields.FIELD_ORDER_ID, orderId)
                .addParam(Fields.FIELD_LIMIT,AppData.Config.PAGE_LIMIT);
        if(!TextUtils.isEmpty(orderPageId))
            builder.addParam(Fields.FIELD_TRADE_ID_PAGE, orderPageId);
        PostParams params = builder.build();
        HttpUtils.getInstance().request(params, OrderDealDetailResponse.class, observer);
    }


    /**
     * 行情指数
     * @param symbolId
     * @param observer
     */
    public static void RequestOptionIndices(String symbolId, SimpleResponseListener<OptionIndicesResponse> observer){
        if(TextUtils.isEmpty(symbolId))
            return;
        GetParams.Builder builder = new BParamsBuilder().get();
        builder.url(Urls.API_OPTION_INDICES)
                .addParam("symbol", symbolId);

        GetParams params = builder.build();
        HttpUtils.getInstance().request(params, OptionIndicesResponse.class, observer);
    }

    public static void RequestOptionCreateOrder(CreateOrderRequest requestData, SimpleResponseListener<OrderBean> listener) {
        PostParams params = BParamsBuilder.post()
                .url(Urls.API_OPTION_ORDER_CREATE)
                .addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
                .addParam(Fields.FIELD_EXCHANGE_ID2, requestData.exchangeId)
                .addParam(Fields.FIELD_SYMBOL_ID, requestData.symbol)
                .addParam(Fields.FIELD_SIDE, requestData.isBuyMode ? "buy" : "sell")
                .addParam(Fields.FIELD_TYPE, requestData.isLimitedPrice ? "limit" : "market")
                .addParam(Fields.FIELD_CLIENT_ORDER_ID, System.currentTimeMillis() + "")
                .addParam(Fields.FIELD_PRICE, requestData.price)
                .addParam(Fields.FIELD_QUANTITY, requestData.amount)
                .build();
        HttpUtils.getInstance().request(params, OrderBean.class, listener);
    }


    public static void RequestOptionCancelAllOrder(String symbols, SimpleResponseListener<ResultResponse> listener){
        PostParams.Builder builder = new BParamsBuilder().post();
        builder.url(Urls.API_OPTION_ORDER_CANCEL_BATCH)
                .addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
                .build();
        if(!TextUtils.isEmpty(symbols))
            builder.addParam("symbol_ids",symbols.toUpperCase());
        PostParams params = builder.build();
        HttpUtils.getInstance().request(params, ResultResponse.class, listener);
    }


    public static void RequestOptionAssetDetail(String token, String pageId, SimpleResponseListener<AssetRecordResponse> observer) {

        PostParams.Builder builder = new BParamsBuilder().post();
        builder.url(Urls.API_OPTION_ASSET_DETAIL)
                .addParam(Fields.FIELD_ACCOUNT_ID, UserInfo.getDefaultAccountId())
                .addParam(Fields.FIELD_LIMIT,AppData.Config.PAGE_LIMIT);
        if(!TextUtils.isEmpty(token))
            builder.addParam("token_id",token);
        if(!TextUtils.isEmpty(pageId))
            builder.addParam(Fields.FIELD_ORDER_ID_PAGE_FROM, pageId);
        PostParams params = builder.build();
        HttpUtils.getInstance().request(params, AssetRecordResponse.class, observer);

    }

    public static void RequestOptionFee(String exchange_id, String symbol_ids, SimpleResponseListener<OptionFeeResponse> observer) {

        PostParams.Builder builder = new BParamsBuilder().post();
        builder.url(Urls.API_OPTION_FEE)
                .addParam(Fields.FIELD_EXCHANGE_ID2, exchange_id)
                .addParam("symbol_ids", symbol_ids)
                .build();
        PostParams params = builder.build();
        HttpUtils.getInstance().request(params, OptionFeeResponse.class, observer);

    }

    public static void RequestOptionSymbols(String symbol_ids, SimpleResponseListener<OptionCoinPairBean> observer) {

        PostParams.Builder builder = new BParamsBuilder().post();
        builder.url(Urls.API_OPTION_SYMBOL)
                .addParam("symbol_ids", symbol_ids)
                .build();
        PostParams params = builder.build();
        HttpUtils.getInstance().request(params, OptionCoinPairBean.class, observer);

    }

    public static void RequestOptionStatus(String symbol_ids, SimpleResponseListener<OptionSymbolStatusBean> observer) {

        PostParams.Builder builder = new BParamsBuilder().post();
        builder.url(Urls.API_OPTION_STATUS)
                .addParam("symbol_ids", symbol_ids)
                .build();
        PostParams params = builder.build();
        HttpUtils.getInstance().request(params, OptionSymbolStatusBean.class, observer);

    }

}
